const { orderBy } = require('lodash');
const { staff_collection, obdLongLat_collection } = require('../config');
const { db } = require('../config');
const { command } = require('../config');
const _ = command;
const fs = require('fs'); // 引入fs模块用来读取文件
const { obd_modify_collection } = require('../config')
var staffName, staffId;
const path = require('path');

// 获取当前文件所在的目录
const directoryPath = path.dirname(__filename);

// 构建JSON文件的完整路径
const filePath = path.join(directoryPath, '1.json');

// 异步延迟函数
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// 读取JSON文件
exports.main = async (event, context) => {
    try {
        // 读取文件
        const data = await new Promise((resolve, reject) => {
            fs.readFile(filePath, 'utf8', (err, data) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(data);
                }
            });
        });

        // 解析JSON数据
        const jsonData = JSON.parse(data);
        var i = 1;

        // 遍历数组并打印所需的字段，每次迭代之间暂停0.5秒
        for (let item of jsonData) {
            console.log('_id:', item._id);
            console.log('workOrderId:', item.workOrderId);
            console.log(i++);
            res = await db.collection(obd_modify_collection).doc(item._id).update({
                workOrderId: item.workOrderId
            });
            console.log('res:', res.updated); // 分隔符
            console.log('---'); // 分隔符

            // 暂停0.5秒
            // await delay(200);
        }
    } catch (err) {
        console.error('Error processing JSON data:', err);
        return {
            statusCode: 500,
            body: JSON.stringify({ error: 'Failed to process JSON data' })
        };
    }

    return {
        statusCode: 200,
        body: JSON.stringify({ message: 'JSON data processed successfully' })
    };
};
// jsonData.forEach(item => {
//     console.log('_id:', item._id);
//     console.log('workOrderId:', item.workOrderId);
//     res = db.collection(obd_modify_collection).doc(item._id).update({
//         workOrderId: item.workOrderId
//     });
//     console.log('res:', res.updated);
//     // 暂停0.5秒
//     delay(1000);
//     // if (res.updated != 1) {
//     //     console.log('_id:', item._id);
//     //     console.log('res:', res);
//     // }
// });